const Koa = require('koa')
const app = new Koa()
/***********************  1  ***************************/
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const abnormal = require('./config/abnormal')

var cors = require('koa-cors')
const mysql = require('mysql');


app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(cors())
app.use(json())
app.use(logger())
app.use(abnormal)
/***********************  1  ***************************/



/***********************  2  ***************************/
/* 引入路由 前台页面*/
const index = require('./routes/front/index')
// 注册路由 后台管理
app.use(index.routes(), index.allowedMethods())


/* 引入路由 后台管理*/
const users = require('./routes/after/index')
const getuinfo = require('./routes/after/getuinfo')
// 注册路由 前台页面
app.use(users.routes(), users.allowedMethods())
app.use(getuinfo.routes(), getuinfo.allowedMethods())

// 添加内容 管理系统
const postuinfo = require('./routes/after/postuinfo')
app.use(postuinfo.routes(), postuinfo.allowedMethods())
// 图片路由
const image = require('./routes/after/img')
app.use(image.routes(), image.allowedMethods())
/***********************  2  ***************************/
// error handler
onerror(app)

// middlewares

app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
/***********************  设置回话  ***************************/
const session = require('koa-session');
app.keys = ['some secret hurr'];
const CONFIG = {
   key: 'koa:sess',   //cookie key (default is koa:sess)
   maxAge: 86400000,  // cookie的过期时间 maxAge in ms (default is 1 days)
   overwrite: true,  //是否可以overwrite    (默认default true)
   httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
   signed: true,   //签名默认true
   rolling: false,  //在每次请求时强行设置cookie，这将重置cookie过期时间（默认：false）
   renew: false,  //(boolean) renew session when session is nearly expired,
};
app.use(session(CONFIG, app));
/***********************  end  ***************************/

// logger
app.use(async (ctx, next) => {
  console.log("请求信息host：",ctx.req.headers.origin);
  ctx.set("Access-Control-Allow-Origin",  ctx.req.headers.origin); //具体的请求路径 "*"
  //正是开发是应当要写 固定 Origin
  ctx.set("Access-Control-Allow-Headers", "x-requested-with");
  ctx.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
  ctx.set('Access-Control-Allow-Credentials',true);
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
